<template>
  <view class="padding-lr-30">
    <view class="card padding-30" :style="{marginTop}">
      <view class="relative flex-row" @click="toDetail">
        <l-avatar :avatar="photo" type="square" size="112rpx" default="https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb_admin_app/static/default.png" />

        <view class="margin-left-20">
          <text class="text-28 color-t1 text-bold">{{ item.number +'('+item.brand + item.seatAmount+'座)' }}</text>
          <view class="margin-top-20 flex-row align-center">
            <image class="driver block" src="https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb_admin_app/icon/icon_driver.png" />
            <text class="text-24 color-t3 margin-left-10">{{ item.driverNickName || '无' }}</text>
          </view>
        </view>

        <view class="flex-row tags">
          <l-tag :text="vehicleStatus.label" :type="vehicleStatus.type" border-width="0" plain />

          <view class="margin-left-20">
            <l-tag :text="publishStatus.label" :type="publishStatus.type" border-width="0" plain />
          </view>

          <view class="margin-left-20">
            <l-tag :text="examineStatus.label" :type="examineStatus.type" border-width="0" plain />
          </view>
        </view>
      </view>

      <!-- 近五日车态 -->
      <view v-if="auth.includes('car_kanban')" class="view-box padding-bottom-30 margin-top-30">
        <scroll-view class="flex-row" :show-scrollbar="false" scroll-x>
          <view class="item-box flex-row">
            <view v-for="(dayStatus, index2) in item.dayStatusList" :key="index2" class="vehicle-day-status-wrap padding-right-20 flex-column">
              <view class="padding-tb-30 flex-row flex-center">
                <text class="text-28" :class="['color-' + (isToday(dayStatus.date, index2) ? 'primary' : 't1')]">{{ dayStatus.date }} {{ isToday(dayStatus.date, index2) ? '今天' : dayStatus.weekText }}</text>
              </view>
              <view class="vehicle-event-list-wrap flex-column justify-center flex-item" :style="{ backgroundColor: dayStatus.eventList.length === 1 && dayStatus.eventList[0].status === 0 ? colors.colorPrimaryFade : colors.colorSuccessFade}" @click="handleEventListClick(item, dayStatus.eventList,dayStatus.date)">
                <view v-for="(event, index3) in dayStatus.eventList" :key="index3" class="flex-column flex-center">
                  <text v-if="event.transferStationType" class="text-28 color-t1">{{ event.startDate }}~{{ event.endDate }} (预计)</text>
                  <text v-else class="text-28 color-t1">{{ event.startDate }}~{{ event.endDate }}</text>
                  <text class="text-28 color-t1 route text-center">{{ event.description || event.itinerary || `${event.startPlace}-${event.endPlace}` }}</text>
                  <text v-if="event.driverName" class="text-28 color-t1 route text-center">司机:{{ event.driverName }}</text>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <view v-if="showButton" class="padding-top-30 flex-row justify-end">
        <view v-if="auth.includes('vehicle_bind_driver')" class="tag">
          <tui-button width="144rpx" height="64rpx" border-radius="8rpx" :size="28" plain type="gray" text="关联司机" @click="linkDriver(item)" />
        </view>
        <view v-if="item.examineStatus == 2 && item.publilshStatus == 0&&auth.includes('vehicle_publish')" class="tag">
          <tui-button width="144rpx" height="64rpx" border-radius="8rpx" :size="28" plain type="gray" text="上架" @click="publishVehicle(item.id)" />
        </view>
        <view v-if="(item.examineStatus == 0 || item.examineStatus == 3)&&auth.includes('vehicle_review_submit')" class="tag">
          <tui-button width="144rpx" height="64rpx" border-radius="8rpx" :size="28" plain type="gray" text="审核" @click="editCar(item.id, 'audit')" />
        </view>
        <view v-if="auth.includes('vehicle_add_order')" class="tag">
          <tui-button width="144rpx" height="64rpx" border-radius="8rpx" :size="28" plain type="gray" text="增加订单" @click="addOrder(item)" />
        </view>
        <view v-if="showMore" class="tag">
          <tui-button width="144rpx" height="64rpx" border-radius="8rpx" :size="28" plain type="gray" text="更多" @click="moreOperate(item)" />
        </view>
      </view>

    </view>
  </view>
</template>

<script>
import colors from '@/common/colors'
import request from '@/common/api/request'
import { mapGetters, mapMutations } from 'vuex'
import { jump, loading, dateFormat } from '@/common/util'
import { publishCar } from '@/common/api/car'
import { vehicleStatus } from '@/vehicle/index'
const moreAuth = ['vehicle_view_order', 'vehicle_repair_plan', 'vehicle_update', 'vehicle_delete', 'vehicle_publish']
export default {
  name: 'CarItem',
  props: {
    item: {
      type: Object,
      default: () => {}
    },
    chooseYear: {
      type: String,
      default: ''
    },
    marginTop: {
      type: String,
      default: '30rpx'
    }
  },
  data() {
    return {
      colors
    }
  },
  computed: {
    isToday() {
      return (date, index) => {
        if (this.chooseYear) {
          date = date.replace('月', '-').replace('日', '')
          date = this.chooseYear + '-' + date
          const today = dateFormat()
          return date === today
        }
        return !index
      }
    },
    photo() {
      if (this.item.photo) {
        const arr = this.item.photo.split(',')
        return arr[0]
      } else {
        return ''
      }
    },
    vehicleStatus() {
      const status = this.item.dayStatusList[0].eventList[0].status
      for (let i = 0; i < vehicleStatus.length; i++) {
        const item = vehicleStatus[i]
        if (item.value === status) return item
      }
      return vehicleStatus[5]
    },
    publishStatus() {
      if (this.item.publilshStatus === 1) return { label: '上架', type: 'success' }
      else return { label: '下架', type: 'secondary' }
    },
    examineStatus() {
      switch (this.item.examineStatus) {
        case 1:
          return { label: '审核中', type: 'primary' }
        case 2:
          return { label: '审核通过', type: 'success' }
        case 3:
          return { label: '审核不通过', type: 'error' }
        default:
          return { label: '未审核', type: 'secondary' }
      }
    },
    showMore() {
      for (let i = 0; i < moreAuth.length; i++) {
        const item = moreAuth[i]
        if (item === 'vehicle_publish' && this.item.publilshStatus === 1 && this.auth.includes(item)) return true
        if (this.auth.includes(item)) return true
      }
      return false
    },
    showButton() {
      let n = 0
      if (this.auth.includes('vehicle_bind_driver')) n++
      if (this.item.examineStatus == 2 && this.item.publilshStatus == 0 && this.auth.includes('vehicle_publish')) n++
      if ((this.item.examineStatus == 0 || this.item.examineStatus == 3) && this.auth.includes('vehicle_review_submit')) n++
      if (this.auth.includes('vehicle_add_order')) n++
      if (this.showMore) n++
      return n
    },
    ...mapGetters({
      auth: 'auth'
    })
  },
  methods: {
    // 关联司机
    linkDriver(rows) {
      jump(`/driver/list/index?directBind=1&type=vehicle&driverId=${rows.driverId || ''}&id=${rows.id}`)
    },
    // 车辆上架、下架
    async publishVehicle(vehicleId) {
      const l = loading('更新中')
      const [err, res] = await publishCar({ vehicleId })
      l.hide()
      if (!request.errorCheck(err, res)) return
      this.$parent.reload()
    },
    // 编辑/审核车辆
    editCar(id, type) {
      jump(`/vehicle/add-vehicle/add-vehicle?id=${id}&type=${type}`)
    },
    // 增加订单跳转
    addOrder(item, date) {
      const obj = {
        vehicleName: item.number + '(' + item.brand + item.seatAmount + '座 )',
        vehicleId: item.id,
        driverName: item.driverNickName || '',
        driverId: item.driverId || ''
      }
      if (date) obj.date = date
      this.setChooseVehicleInfo(obj)
      jump('/order/add-new/add-new?type=vehicle')
    },
    // 更多
    moreOperate(item) {
      this.$emit('more', item)
    },
    // 车态点击事件
    handleEventListClick(vehicle, eventList, date) {
      const year = new Date().getFullYear()
      date = date.replace(/([月])/g, '-')
      date = date.replace(/([日])/g, '')
      date = year + '-' + date
      // 车辆待命点击新增内部订单
      if (eventList.length === 1 && eventList[0].status === 0) {
        this.addOrder(vehicle, date)
        return
      } else {
        const actionSheetItemList = []
        const orderArr = []
        const repairPlanArr = []
        eventList.forEach(item => {
          // 订单
          if (item.targetType === 4) {
            orderArr.push(item)
          } else if (item.targetType === 2) {
            repairPlanArr.push(item)
          }
        })
        if (orderArr.length === 1) {
          actionSheetItemList.push({ text: '查看订单' })
        } else if (orderArr.length > 1) {
          orderArr.forEach((order, index) => actionSheetItemList.push({ text: `查看订单${index + 1}` }))
        }
        if (repairPlanArr.length) {
          actionSheetItemList.push({ text: '查看维修计划' })
        }

        actionSheetItemList.push({ text: '新增内部订单' })

        if (orderArr.length || repairPlanArr.length) {
          this.$emit('showAction', {
            list: actionSheetItemList,
            item: vehicle,
            date,
            orderArr
          })
        }
      }
    },
    toDetail() {
      jump(`/vehicle/vehicle-detail/vehicle-detail?id=${this.item.id}`)
    },
    ...mapMutations({
      setChooseVehicleInfo: 'order/setChooseVehicleInfo'
    })
  }
}
</script>

<style scoped lang="scss">
.card{
  border-radius:20rpx;
}
.driver{
  width:28rpx;
  height:28rpx;
}
.tags{
  @include position(absolute, $right:0, $bottom:0);
}
.view-box{
  border-top: 2rpx solid $color-border;
  border-bottom: 2rpx solid $color-border;
}
.item-box{
  width:1380rpx;
}
.vehicle-day-status-wrap {
  width: 280rpx;
}
.vehicle-event-list-wrap {
  min-height: 160rpx;
  padding: 16rpx;
  border-radius: 10rpx;
}
.tag{
  margin:0 6rpx;
}
</style>
